package pl.edu.agh.ki.ewywiadowka.client.windows;

import java.util.LinkedList;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gen2.table.client.FixedWidthFlexTable;
import com.google.gwt.gen2.table.client.FixedWidthGrid;
import com.google.gwt.gen2.table.client.ScrollTable;
import com.google.gwt.gen2.table.client.AbstractScrollTable.SortPolicy;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTMLTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SourcesTableEvents;
import com.google.gwt.user.client.ui.TableListener;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.HTMLTable.ColumnFormatter;
import com.google.gwt.gen2.table.override.client.HTMLTable.RowFormatter;

import pl.edu.agh.ki.ewywiadowka.client.Const;
import pl.edu.agh.ki.ewywiadowka.client.EWywiadowka;
import pl.edu.agh.ki.ewywiadowka.client.dto.ClassDTO;
import pl.edu.agh.ki.ewywiadowka.client.dto.StudentDTO;
import pl.edu.agh.ki.ewywiadowka.client.windows.educator.EducatorMarksWelcomeWindow;
import pl.edu.agh.ki.ewywiadowka.client.windows.secretary.ModifyStudentWindow;


/**
 * 
 * Klasa dostaje w konstutorze parametr mode, od ktorego zalezy do czego wykorzystujemy to okno
 * Mozliwe wartosci mode:
 * 1 - modyfikacja danych ucznia
 * 2 - usuniecie ucznia z systemu
 * 3 - wysiwetlenie ocen jednostkowych ucznia
 * 4 - wyswietlenie ocen koncowych ucznia
 * 
 * @author pimol
 *
 */
public class SearchStudentWindow extends GenericWindow implements ClickHandler,
		TableListener {

	private ScrollPanel _mainPanel = new ScrollPanel();
	private DockPanel _dockPanel = new DockPanel();

	private HorizontalPanel _filterHorizontalPanel = new HorizontalPanel();
	private Grid _formular;
	private ScrollTable _scrollTable = null;
	private Button _okButton = new Button("Wybierz ucznia");
	private Button _filterButton = new Button("Filtruj");
	private Button _addMarkButton = new Button("Dodaj ocene");
	private Button _modifyRemoveMarkButton = new Button("Przegladaj/usun oceny");

	private TextBox _nameTextBox = new TextBox();
	private TextBox _surnameTextBox = new TextBox();
	private TextBox _numberTextBox = new TextBox();
	private TextBox _annualTextBox = new TextBox();
	private TextBox _classTextBox = new TextBox();
	private TextBox _loginTextBox = new TextBox();
	private FixedWidthGrid _dataTable;
	private FixedWidthFlexTable _headerTable;

	private int _selectedRow = -1;

	private SearchStudentWindow _me;

	private LinkedList<StudentDTO> _students = null; // bo na poczatku nie ma

	private int _mode = -1;

	public SearchStudentWindow(EWywiadowka wywiadowka, int mode) {
		super(wywiadowka);

		_me = this;

		_mode = mode;

		_formular = new Grid(2, 6);
		_formular.setWidget(0, 0, new Label("Imię"));
		_formular.setWidget(1, 0, new Label("Nazwisko"));
		_formular.setWidget(0, 2, new Label("Numer legitymacji"));
		_formular.setWidget(1, 2, new Label("Rocznik"));
		_formular.setWidget(0, 4, new Label("Klasa"));
		_formular.setWidget(1, 4, new Label("Login"));

		_formular.setWidget(0, 1, _surnameTextBox);
		_formular.setWidget(1, 1, _nameTextBox);
		_formular.setWidget(0, 3, _numberTextBox);
		_formular.setWidget(1, 3, _annualTextBox);
		_formular.setWidget(0, 5, _classTextBox);
		_formular.setWidget(1, 5, _loginTextBox);

		_filterButton.addClickHandler(this);
		_okButton.addClickHandler(this);
		_addMarkButton.addClickHandler(this);
		_modifyRemoveMarkButton.addClickHandler(this);

		_filterHorizontalPanel.add(_formular);
		_filterHorizontalPanel.add(_filterButton);

		_dataTable = new FixedWidthGrid(0, 5);
		_dataTable.setBorderWidth(1);

		_headerTable = new FixedWidthFlexTable();
		_headerTable.setBorderWidth(1);
		fillHeader();

		_scrollTable = new ScrollTable(_dataTable, _headerTable);
		_scrollTable.fillWidth();
		_scrollTable.setHeight("400px");

		_dockPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		_dockPanel.add(_filterHorizontalPanel, DockPanel.NORTH);
		_dockPanel.add(_scrollTable, DockPanel.CENTER);
		if (_mode < 3)
			_dockPanel.add(_okButton, DockPanel.SOUTH);
		else {
			HorizontalPanel hPanel = new HorizontalPanel();
			hPanel.add(_addMarkButton);
			hPanel.add(_modifyRemoveMarkButton);
			_dockPanel.add(hPanel, DockPanel.SOUTH);
		}

		_mainPanel.add(_dockPanel);
		this.initWidget(_mainPanel);
	}

	private void repaintTable() {
		int i = 0;
		for (StudentDTO student : _students)
			fillRow(i++, student);
	}

	private void fillRow(int row, StudentDTO student) {
		
		ClassDTO clas = student.clas;

		RowFormatter rowFormatter = _dataTable.getRowFormatter();

		if (row % 2 == 0)
			rowFormatter.addStyleName(row, "tableRowStyle1");
		else
			rowFormatter.addStyleName(row, "tableRowStyle2");

		_dataTable.setHTML(row, 0, student.name.toString());
		_dataTable.setHTML(row, 1, student.surname.toString());
		_dataTable.setHTML(row, 2, clas.letter.toString());
		_dataTable.setHTML(row, 3, clas.annual.toString());
		_dataTable.setHTML(row, 4, student.numer.toString());
	}

	private void fillHeader() {
		_headerTable.setHTML(0, 0, "Imię");
		_headerTable.setHTML(0, 1, "Nazwisko");
		_headerTable.setHTML(0, 2, "Klasa");
		_headerTable.setHTML(0, 3, "Rocznik");
		_headerTable.setHTML(0, 4, "Nr legitymacji");
	}

	private void getStudents() {
		Const.eWywiadowkaService
				.getStudents(new AsyncCallback<LinkedList<StudentDTO>>() {

					@Override
					public void onFailure(Throwable caught) {
						Window.alert(caught.getMessage());
					}

					@Override
					public void onSuccess(LinkedList<StudentDTO> result) {

						_students = result;

						_headerTable = new FixedWidthFlexTable();
						_headerTable.setBorderWidth(1);
						fillHeader();

						_dataTable = new FixedWidthGrid(_students.size(), 5);
						_dataTable.setBorderWidth(1);
						repaintTable();

						_dockPanel.remove(_scrollTable);

						_scrollTable = new ScrollTable(_dataTable, _headerTable);
						_scrollTable.setHeight("400px");
						_scrollTable.setVisible(true);

						_dataTable.addTableListener(_me);
						_scrollTable.setSortPolicy(SortPolicy.DISABLED);

						_dockPanel.add(_scrollTable, DockPanel.CENTER);
						_scrollTable.fillWidth();
					}

				});
	}

	private Const.FormularMessages verifyFormular() {
		return Const.FormularMessages.OK;
	}

	public void onClick(ClickEvent event) {
		if (event.getSource() == _filterButton) {
			Const.FormularMessages msg;
			if ((msg = verifyFormular()) == Const.FormularMessages.OK)
				getStudents();
			else
				Window.alert(msg.toString());
		} else {

			if (event.getSource() == _okButton) {
				if (_selectedRow == -1) {
					Window.alert("Prosze wybrac ucznia");
				} else {
					final StudentDTO student = _students.get(_selectedRow);
					Window.alert("Wybrano ucznia: \n" + student.toString());

					_mainPanel.remove(_dockPanel);

					if (_mode == 1) { // modyfikacja
						_mainPanel.add(new ModifyStudentWindow(getWywiadowka(),
								student));
					} else if (_mode == 2) { // usuniecie
						Const.eWywiadowkaService.removeStudent(student,
								new AsyncCallback<Const.Error.StudentRemoveMsg>() {

									@Override
									public void onFailure(Throwable caught) {
										Window.alert(caught.getMessage());
									}

									@Override
									public void onSuccess(Const.Error.StudentRemoveMsg result) {
										Window.alert(result.toString());

										_mainPanel.add(new SearchStudentWindow(
												getWywiadowka(), 2));
									}

								});
					}
				}
			} else if (event.getSource() == _modifyRemoveMarkButton) {
				if (_selectedRow == -1) {
					Window.alert("Prosze wybrac ucznia");
				} else {
					final StudentDTO student = _students.get(_selectedRow);
					Window.alert("Wybrano ucznia: \n" + student.toString());

					_mainPanel.remove(_dockPanel);

					if (_mode == 3) //oceny jednostkowe
						_mainPanel.add(new EducatorMarksWelcomeWindow(
								getWywiadowka(), getWywiadowka()._clas, 1));
					else if (_mode == 4) { //oceny koncowe
						//_mainPanel.add(new StudentMarksFinalWelcomeWindow(
						//		getWywiadowka(), student));
					}
				}
			} else if (event.getSource() == _addMarkButton) {
				if (_selectedRow == -1) {
					Window.alert("Prosze wybrac ucznia");
				} else {
					final StudentDTO student = _students.get(_selectedRow);
					Window.alert("Wybrano ucznia: \n" + student.toString());

					_mainPanel.remove(_dockPanel);
					
			//		if (_mode == 3)
//						_mainPanel.add(new StudentMarksSingleAddWindow(
	//							getWywiadowka(), student));
				}
			}
		}
	}

	@Override
	public void onCellClicked(SourcesTableEvents sender, int row, int cell) {
		RowFormatter rowFormatter = _dataTable.getRowFormatter();
		if (_selectedRow != -1) {
			if (_selectedRow % 2 == 0)
				rowFormatter.setStyleName(_selectedRow, "tableRowStyle1");
			else
				rowFormatter.setStyleName(_selectedRow, "tableRowStyle2");
		}
		_selectedRow = row;
		rowFormatter.setStyleName(row, "clickedTableRowStyle");
	}
}
